import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpServicesProvider } from "../../providers/http-services/http-services";
import { UtilsProvider } from "../../providers/utils/utils";
import { ValidateProvider } from "../../providers/validate/validate";
import { ConfigProvider } from "../../providers/config/config";
import { StorageProvider } from "../../providers/storage/storage";

/**
 * Generated class for the TasksDetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
declare var BMap;
@IonicPage({
  segment: 'tasks/tasksDetail/:id',
  defaultHistory: [ 'HomePage','TaskPage']
})
@Component({
  selector: 'page-tasks-detail',
  templateUrl: 'tasks-detail.html',
})


export class TasksDetailPage {

  mk: any;
  amoy_id="0";
  token: string;
  status="0";
  searchParams = {};
  userInfo = {};
  dataInfo = {
    status: 0,
    remain_num: 0
  };
  sentInfo = {
    status: '0',
    summary: 0,
    company_photo: '',
    company_name: ''
  };
  company_name = '';
  company_photo = ''
  company_lon = '';
  company_lat = '';
  summary = '';
  geolocation;
  constructor(public navCtrl: NavController,
    public httpService: HttpServicesProvider,
    public config: ConfigProvider,
    public validate: ValidateProvider,
    public util: UtilsProvider,
    public storage: StorageProvider,
    public navParams: NavParams) {
  }
  //判断用户是否登录
  ionViewCanEnter(): boolean {
    return this.validate.checkLogin();
  }
  ionViewWillEnter() {

  }
  ionViewDidLoad() {
    this.amoy_id = this.navParams.get('id');
    this.status =  this.navParams.get('status');
    this.token = this.config.getToken();
    this.userInfo = JSON.parse(this.storage.get('userInfo'));
    this.getData();

  }
  /**
 * 页面加载获取数据
 * */
  getData() {
    //获取任务信息列表
    let params;
    if(this.status=='0'){
       params = {
        token: this.token,       
        mission_id: this.amoy_id
      };
    }else{
      params = {
        token: this.token,       
        employee_id: this.amoy_id
      };
    }
   
    Object.assign(params, this.searchParams);

    let loading = this.util.loading();
    loading.show();
    this.httpService.requestPostData('/mul_mission/mission_detail', params, response => {
      loading.close();
      if (response['error'] == 200) {
        this.dataInfo = response['data']['mission_info'];
        this.sentInfo = response['data']['employee_info'];
        this.getMap();
        //全部数据
      } else {
        this.util.presentAlert(response.message);
      }
    });
  }

  /**
    * 图片上传
    * */
  uploadImage(e) {
    let file = e.target.files[0];
    let data = new FormData();
    data.append('image', file);
    data.append('type', 'moments');
    this.httpService.uploadImage('/user/upload_file', data, result => {
      this.company_photo = result.img_path;
    });

  }

  delImage(item, value) {
    this.util.presentConfirm('确定删除吗？', () => {
      // let index = this.util.inArray(this.infoData[item.letter], value);
      // if (index > -1) {
      //     this.infoData[item.letter].splice(index, 1);
      // }
      this.company_photo = ''
    });
  }

  getMap() {
    // 百度地图API功能
    let map = new BMap.Map("map");
    let point = new BMap.Point(112.55086359, 37.89027705);
    map.centerAndZoom(point, 16);
    this.geolocation = new BMap.Geolocation();
    let that = this;
    if(that.sentInfo.status=='0'){
      this.geolocation.getCurrentPosition((r) => {
        if (this.geolocation.getStatus() == 0) {
          // var myIcon = new BMap.Icon('',new BMap.Size(100,80));              
          let myIcon = new BMap.Icon("./assets/imgs/dw.png", new BMap.Size(30,30));
          that.mk = new BMap.Marker(r.point,{icon:myIcon});
          map.addOverlay(that.mk);
          map.panTo(r.point);
          that.mk.enableDragging()
          // map.addEventListener('ontouchstart', function () {
          //   map.panTo(that.mk['point']);
          // });
          map.addEventListener("dragend",function(e){
            // alert("当前地图中心点：" + map.getCenter().lng + "," + map.getCenter().lat);
            map.clearOverlays();
            let marker = new BMap.Marker(new BMap.Point(map.getCenter().lng, map.getCenter().lat),{icon:myIcon});
            map.addOverlay(marker);
            map.panTo(marker.point);
            marker.enableDragging()
          });
          map.addEventListener("zoomend",function(e){
            // alert("当前地图中心点：" + map.getCenter().lng + "," + map.getCenter().lat);
            map.clearOverlays();
            let marker = new BMap.Marker(new BMap.Point(map.getCenter().lng, map.getCenter().lat),{icon:myIcon});
            map.addOverlay(marker);
            map.panTo(marker.point);
            marker.enableDragging()
          });
        }else {
          alert('failed' + this.geolocation.getStatus());
        }
      })
    }else{
      let myIcon = new BMap.Icon("./assets/imgs/dw.png", new BMap.Size(30,30));
      let marker = new BMap.Marker(new BMap.Point(this.sentInfo['lon'], this.sentInfo['lat']),{icon:myIcon});      
      map.addOverlay(marker);
      map.panTo(marker.point);
    }

  }

  goPage(page, data = {}) {
    this.navCtrl.push(page, data)
  }
  // 提交
  submitData() {
    if (this.dataInfo.remain_num == 0) {
      this.util.presentAlert("没有任务名额啦!");
      return false;
    }
    let loading = this.util.loading();
    loading.show();
    this.httpService.requestPostData('/mul_mission/mission_apply',
      {
        token: this.token,
        mission_id: this.amoy_id,
        company_name: this.company_name,
        company_photo: this.company_photo,
        lon: this.mk['point'].lng,
        lat: this.mk['point'].lat,
        summary: this.summary
      }, response => {
        loading.close();
        if (response['error'] == 200) {
          this.util.presentAlert(response.message);
          this.getData();
        } else {
          this.util.presentAlert(response.message);
        }
      });
  }
}
